import { Button, Table, message } from "antd";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import moment from "moment";
import React, { PureComponent } from "react";
import styles from "./index.less";
import enums from "../creditCar/enums";
import Ellipsis from "@/components/Ellipsis";
import PropTypes from "prop-types";
import { getDicByKey, getDictOptionsByCode } from '@/support/common';
import MaskText from '@/components/MaskText'

function toCamel(str) {
  return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
    return $1 + $2.toUpperCase();
  });
}

const regExpFields = {
  position_address: 'location',
  lng: 'longitude',
  lat: 'latitude',
  vehicle_owner_name: 'name',
  vehicle_owner_phone: 'phone',
  id_num: 'identity'
}

@connect((state) => ({
  overdueCar: state.overdueCar,
  menu: state.menu,
  warningRecord: state.warningRecord,
}))
export default class OverdueCarDetail extends PureComponent {
  static contextTypes = {
    authButton: PropTypes.array,
    dicData: PropTypes.any,
  };
  state = {
    vin: "",
    isEdit: false,
    detailData: {},
    statuesData: {},
    submitBntLading: false,
    detailDataNew: [],
    riskOperateShow: false,
    riskWarnShow: false,
    filterItem: ["risk_warn_show", "risk_operate_show"],
    tableData: [],
    curPage: 1,
    pageSize: 10,
    total: 0,
  };
  addPreinstall = (columns) => {
    return columns.map((i) => {
      const sameTitle = columns.some(
        (j) => j.name === i.name && i.fieldId !== j.fieldId
      );
      if (sameTitle && i.fieldId) {
        i.name = `${i.name}(预设)`;
      }
      return i;
    });
  };
  componentDidMount() {
    let vin = sessionStorage.getItem("vin");
    vin = JSON.parse(vin);
    const typeOption = sessionStorage.getItem("typeOption");
    this.setState({ creditTypeOptions: JSON.parse(typeOption)});
    this.setState({ vin });
    this.props.dispatch({
      // 更多筛选数据
      type: "overdueCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/credit/merchant/field/scenelist?menu=overdue&scene=detail",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          if (response.data && response.data.length > 0) {
            if (response.data.some((i) => i.column == "risk_operate_show")) {
              this.setState({ riskOperateShow: true });
              this.queryRecordList();
            }
            if (response.data.some((i) => i.column == "risk_warn_show")) {
              this.setState({ riskWarnShow: true });
              this.handleTableData();
            }
              // 脱敏字段添加正则校验类型
              let enhanceData = response.data.map(item => {
                if(regExpFields[item.column]) {
                  return {
                    ...item,
                    regExpType: regExpFields[item.column]
                  }
                }
                return item;
              })
            this.setState({
              fieldDetail: this.addPreinstall(
                enhanceData.filter(
                  (i) => !this.state.filterItem.some((j) => i.column == j)
                )
              ),
            });
            this.handleGetVehicleDetail(vin);
          }
        } else {
          message.error(response.statusMessage);
        }
      },
    });
    const detailData = sessionStorage.getItem("overdueCarDetail") || "{}";
    this.setState(
      {
        vin: vin,
        // detailData: JSON.parse(detailData)
      },
      () => {
        // this.handleGetVehicleStatues(JSON.parse(vin));
        // this.handleGetVehicleDetail(JSON.parse(vin))
        // this.queryRecordList()
      }
    );
    // this.handleGetVehicleStatues(vin);
  }

  handleTableData = () => {//预警信息列表
    const { curPage, pageSize } = this.state;
    const vin = this.state.vin;

    this.setState({
      tableLoading: true,
    });

    let submitData = { vin, curPage, pageSize };

    this.props.dispatch({
      type: "overdueCar/postObjWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/risk/warn/record/page",
        ...submitData,
      },
      callback: (response) => {
        if (response && response.statusCode == "0" && response.data) {
          if (
            response.data.rows.length === 0 &&
            response.data.pagination.current > 1
          ) {
            this.setState(
              {
                curPage: 1,
                pageSize: 10,
              },
              () => {
                this.handleTableData();
              }
            );
          } else {
            this.setState({
              tableData: response.data.rows,
              total: response.data.pagination.total,
            });
          }
        } else {
          if (response.statusCode !== "0") {
            message.error(response.statusMessage);
          }
        }
        this.setState({
          tableLoading: false,
        });
      },
    });
  };

  handleGetVehicleDetail = (vin) => {//详情
    this.props.dispatch({
      type: "overdueCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/overdue/detail",
        vin: vin,
        businessCode: "overdue",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          const specialData = this.specialDataGenrator();
          if (response.data.overdueDate) {
            response.data.overdueDate = moment(response.data.overdueDate);
          }
          if (response.data.financeBeginDate) {
            response.data.financeBeginDate = moment(
              response.data.financeBeginDate
            ).format("YYYY-MM-DD");
          }
          if (response.data.positionDate) {
            response.data.positionDate = moment(
              response.data.positionDate
            ).format("YYYY-MM-DD HH:mm:ss");
          }
          let detailData = response.data;
          if (response.data.fenceInfo && response.data.fenceInfo.length >0) {
            let regExpKeys = Object.keys(regExpFields).map(key => toCamel(key))
            const list = response.data.fenceInfo;
          const keylist = list[0];
          const obj = {}
          for(let key in keylist){
             list.map(item =>{
                if(!obj[key]){
                  obj[key]=[];
                }
                if(item[key]){
                 obj[key].push(item[key])
                }else{
                  obj[key].push('暂无信息')
                }
             })
           }
           for(let key in obj){
            if(obj[key] && obj[key].length >0){
                const newValue = obj[key].join('/')
                if(regExpKeys.includes(key)) {
                  obj[key]= newValue
                } else {
                  obj[key]=<Ellipsis length={18} tooltip>{newValue}</Ellipsis>;
                }
            }
           }
           detailData =  Object.assign(response.data, obj);
          }
          const newDatas = this.createDetail(
            detailData,
            this.state.fieldDetail,
            specialData
          );
          this.setState({
            detailDataNew: newDatas,
            isEdit: false,
            detailData: response.data,
          });
          // this.handleGetVehicleStatues(vin);
          // this.queryRecordList();
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  createDetail = (detailData, fieldDetail, specialData) => {
    if (detailData.warnType == 2 && detailData.warnStatus == 1) {
      fieldDetail.push({
        column: "last_ack_date",
        createDate: detailData.lastAckDate,
        extra: null,
        groupName: "车辆风控信息",
        name: "车机告警最新回执时间",
        type: 6,
      });
    }
    // console.log(specialData);
    const _cc = fieldDetail.reduce((total, currentValue) => {
      const info = detailData[toCamel(currentValue.column)];
      const speInfo = specialData.find((i) => i.column == currentValue.column);
      const item = { ...currentValue, ...speInfo, info };
      let flag = true;
      total = total.map((i) => {
        if (i.groupName == currentValue.groupName) {
          flag = false;
          i.list.push(item);
        }
        return i;
      });
      if (flag) {
        total.push({
          groupName: currentValue.groupName,
          list: [item],
        });
      }
      return total;
    }, []);
    return _cc;
  };

  specialDataGenrator = () => {
    // 生成特殊字段
    return [
      {
        column: "limp_enable",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: "0",
              label: "不支持",
            },
            {
              value: "1",
              label: "支持",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        // 实车当前状态
        column: "vhl_current_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: 0,
              label: "正常",
            },
            {
              value: 1,
              label: "锁车",
            },
            {
              value: 2,
              label: "跛行",
            },
            {
              value: 3,
              label: "待车辆反馈",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
        filterType: 1,
      },
      {
        column: "repayment_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              // 0-还款中；1-已逾期；2-已结清；3-融资已到期
              value: "0",
              label: "还款中",
            },
            {
              value: "1",
              label: "已逾期",
            },
            {
              value: "99",
              label: "未知",
            },
            {
              value: "2",
              label: "已结清",
              hideInOption: true,
            },
            {
              value: "3",
              label: "融资已到期",
            },
          ],
        },
        nullValue: "未知",
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "risk_warn_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              // 1：预警  0或null：未预警 ；
              value: "0",
              label: "未预警",
            },
            {
              value: "1",
              label: "预警",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "engine_state",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              //  2-点火；0-熄火
              value: "0",
              label: "熄火",
            },
            {
              value: "2",
              label: "点火",
            },
            {
              value: "",
              label: "行驶中",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "risk_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              //   0-正常行驶，1-锁车，2-跛行
              value: "0",
              label: "正常行驶",
            },
            {
              value: "1",
              label: "锁车",
            },
            {
              value: "2",
              label: "跛行",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "warn_type",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: 0,
              label: "暂不支持",
            },
            {
              value: 1,
              label: "不可配置",
            },
            {
              value: 2,
              label: "可配置",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "warn_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: 0,
              label: "正常",
            },
            {
              value: 1,
              label: "车机告警",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "credit_type",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: this.state.creditTypeOptions,
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
    ];
  };

  componentWillMount() {}
  // handleGetVehicleDetail2 = (vin) => {
  //   this.props.dispatch({
  //     type: "http2/postDataWithRes2",
  //     payload: {
  //       url: "/mscreditvehicle/credit/vehicle/detail",
  //       vin: vin,
  //     },
  //     callback: (response) => {
  //       if (response && response.statusCode == "0") {
  //         if (response.data.overdueDate) {
  //           response.data.overdueDate = moment(response.data.overdueDate);
  //         }
  //         if (response.data.financeBeginDate) {
  //           response.data.financeBeginDate = moment(
  //             response.data.financeBeginDate
  //           ).format("YYYY-MM-DD");
  //         }
  //         if (response.data.positionDate) {
  //           response.data.positionDate = moment(
  //             response.data.positionDate
  //           ).format("YYYY-MM-DD HH:mm:ss");
  //         }
  //         this.setState({
  //           detailData: { ...response.data, ...this.state.detailData },
  //         });
  //       } else {
  //         message.error(response.statusMessage);
  //       }
  //     },
  //   });
  // };
  // handleGetVehicleStatues = (vin) => {
  //   this.props.dispatch({
  //     type: "http2/getDataWithRes",
  //     payload: {
  //       url: "/third/credit/vehiclestatus",
  //       vin: vin,
  //     },
  //     callback: (response) => {
  //       if (response && response.statusCode == "0" && response.data.status) {
  //         this.setState({
  //           statuesData: response.data.status,
  //         });
  //       } else {
  //         if (response.statusCode != "0") {
  //           message.error(response.statusMessage);
  //         }
  //       }
  //     },
  //   });
  // };
  handleOnReturn = () => {
    const backPath =
      sessionStorage.getItem("backPath") ||
      "/thirdOrgCreditVehicle/thirdOrgCreditVehicleOverdueCar";
    this.props.dispatch(
      routerRedux.push({
        pathname: backPath,
      })
    );
  };
  queryRecordList = () => {
    const { dispatch } = this.props;
    const { vin } = this.state;

    dispatch({
      type: "warningRecord/riskResultList",
        payload: {
        url: '/mscreditbusiness/vehicle/risk/warn/result/page',
        businessCode: "over-due-log",
        curPage: 1,
        pageSize: 10,
        vin,
      },
    });
  };
  handleTableChangeA = (page) => {
    const { dispatch } = this.props;
    const { vin } = this.state;
    const params = {
      businessCode: "over-due-log",
      curPage: page.current,
      pageSize: page.pageSize,
      vin,
    };
    dispatch({
      ype: "warningRecord/riskResultList",
      payload: {
      url: '/mscreditbusiness/vehicle/risk/warn/result/page',
      ...params
  },
    });
  };

  render() {
    const {
      isEdit,
      detailData,
      submitBntLading,
      statuesData,
      total,
      curPage,
      pageSize,
    } = this.state;
    const riskStatusHash = {
      0: "正常行驶",
      1: "锁车",
      2: "跛行",
    };
    const engineStatusHash = {
      0: "熄火",
      2: "点火",
      "": "行驶中",
    };
    const {
      warningRecord: {
        // detailLoading ,
        riskResultList,
        pagination,
      },
    } = this.props;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>
          共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条
        </span>
      ),
    };
    const columnsA = [
      {
        title: "序号",
        dataIndex: "num",
        width: "7%",
        render: (text, record, index) => {
          return pagination.pageSize * (pagination.current - 1) + index + 1;
        },
      },
      {
        title: "执行时间",
        dataIndex: "operateTime",
        render: (text, record) => moment(text).format("YYYY-MM-DD HH:mm:ss"),
      },
      { 
        title: "执行人",
        dataIndex: "operator",
        render(val) {
          return <MaskText text={val} type="name" />;
        } 
      },
      { title: "风控实施记录", dataIndex: "operationContent" },
    ];

    const columnsB = [
      {
        title: "预警时间",
        dataIndex: "riskTriggerDate",
        render: (text) => {
          if (text) {
            return moment(text).format("YYYY-MM-DD HH:mm:ss");
          }
        },
      },
      {
        title: "预警内容",
        dataIndex: "riskWarnMsg",
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: "触发的异常事件",
        dataIndex: "riskEventContent",
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: "已实施的管控措施",
        dataIndex: "riskControlResult",
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: "处理状态",
        dataIndex: "dealStatus",
        render: (text, record) => {
          let findText = enums.dealStatus.array.find((e) => e.value === text);
          return findText ? findText.label : text;
        },
      },
    ];

    const paginationB = {
      showSizeChanger: true,
      total: total,
      current: curPage,
      pageSize: pageSize,
      showTotal: () => {
        return <span>共&nbsp;{total}&nbsp;条</span>;
      },
    };
    const wrningTableProps = {
      columns: columnsB,
      pagination: paginationB,
      rowKey: "sid",
      scroll: { x: "max-content" },
      // loading: tableLoading,
      dataSource: this.state.tableData,
      onChange: (pagination) => {
        this.setState(
          {
            curPage: pagination.current,
            pageSize: pagination.pageSize,
          },
          () => {
            this.handleTableData();
          }
        );
      },
    };
    return (
      <div className={styles.root}>
        <div className={styles.topBtn}>
          <Button type="primary" onClick={() => this.handleOnReturn()}>
            返回
          </Button>
        </div>
        <div className={styles.midContent}>
          {this.state.detailDataNew.map((i) => (
            <div key={`groupName${i.groupName}`} className={styles.publicItem}>
              <div className={styles.itemTitle}>{i.groupName}</div>
              <div className={styles.itemContent}>
                {i.list.map((j) => (
                  <div
                    key={`list${j.column}`}
                    className={styles.itemContentRow}
                  >
                    <div className={styles.rowTitle}>{j.name}:</div>
                    <div className={styles.rowValue}>
                      {j.type == 4 &&
                        j.info &&
                        (typeof j.info == "number"
                          ? moment(j.info).format("YYYY-MM-DD")
                          : moment(j.info, "YYYY-MM-DD").format("YYYY-MM-DD"))}
                      {j.type == 5 &&
                        j.info &&
                        (typeof j.info == "number"
                          ? moment(j.info).format("HH:mm:ss")
                          : moment(j.info, "HH:mm:ss").format("HH:mm:ss"))}
                      {j.type == 6 &&
                        j.info &&
                        (typeof j.info == "number"
                          ? moment(j.info).format("YYYY-MM-DD HH:mm:ss")
                          : moment(j.info, "YYYY-MM-DD HH:mm:ss").format(
                              "YYYY-MM-DD HH:mm:ss"
                            ))}
                      {j.type == 2 &&
                        j.extra &&
                        (j.info !== null
                          ? typeof j.extra == "string"
                            ? j.info !== null
                            : j.extra.optionList.find((n) => n.value == j.info)
                            ? j.extra.optionList.find((n) => n.value == j.info)
                                .label
                            : j.info
                          : j.nullValue || "")}
                      {j.type == 7 && j.info && (
                        <a href={`${j.info}`} target="_blank">
                          {j.info}
                        </a>
                      )}
                      {j.type != 2 &&
                        j.type != 4 &&
                        j.type != 5 &&
                        j.type != 6 &&
                        j.type != 7 &&
                        (j.regExpType ? <MaskText text={j.info} type={j.regExpType} />: (j.info || j.info === 0 ? j.info : ""))}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
        {this.state.riskOperateShow && (
          <div className={styles.midContent} style={{ paddingTop: "20px" }}>
            <div className={styles.publicItem}>
              <div className={styles.itemTitle}>风控操作记录列表</div>
              <div className={styles.itemContent}>
                <div
                  className={styles.itemContentRow}
                  style={{ width: "100%" }}
                >
                  <Table
                    style={{ width: "100%" }}
                    // loading={detailLoading}
                    columns={columnsA}
                    dataSource={riskResultList}
                    pagination={paginationProps}
                    onChange={this.handleTableChangeA}
                  />
                </div>
              </div>
            </div>
          </div>
        )}

        {this.state.riskWarnShow && (
          <div className={styles.midContent} style={{ paddingTop: "20px" }}>
            <div className={styles.publicItem}>
              <div className={styles.itemTitle}>预警信息列表</div>
              <div className={styles.itemContent}>
                <div
                  className={styles.itemContentRow}
                  style={{ width: "100%" }}
                >
                  <Table style={{ width: "100%" }} {...wrningTableProps} />
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  }
}
